<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2006/12/06 14:34:43 $)
// $RCSfile: purge_attachments.php,v $ : $Revision: 1.1 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}
if (!$staffauth->isAdmin()) {
	trigger_error("You do not have permission to access $PHP_SELF", E_USER_ERROR);
}
require_once ("./modules/tickets/functions_tickets.php");
require_once ("./includes/functions_html.php");
require_once ("./includes/functions_template.php");
require_once ("./modules/tickets/functions_ticketsui.php");
require_once ("./modules/tickets/functions_ticketcore.php");

require_once ("./modules/tickets/functions_ticketsearch.php");
?><script language="Javascript" src="<?php echo $_SWIFT["themepath"]; ?>main.js"></script><?

$template->loadLanguageSection("tickets");
$template->loadLanguageSection("staff_attach");

function attachentsearch($searchrules, $rulematch = "all")
	{
		$attachmentidlist = array();
		global $dbCore, $_SWIFT;

		if (!_is_array($searchrules))
		{
			return false;
		}

		if ($rulematch == "all")
		{
			$oper = "AND";
		} else {
			$oper = "OR";
		}
		$_start = fetchmicrotime();

		foreach ($searchrules as $key=>$val)
		{
			switch ($val[0])
			{
				case "filename":
					$_sql[] = buildSearchSQL("filename", $val[1], $val[2]);
				break;
				case "size";
					$_sql[] = buildSearchSQL("filesize", $val[1], ($val[2]*1024));
				break;
				case "dateline":
				$_sql[] = buildSearchSQL("dateline", $val[1], iif(!empty($val[2]), getCalendarDateline($val[2]), DATENOW));
				break;
				case "ticketid":
				$_result  = searchTicketID($val[2]);
				$_sql[] = buildSearchSQL("ticketid", $val[1], $_result["ticketid"]);
				break;
			}
		}

		$query = "SELECT `attachmentid`, `ticketid` FROM `". TABLE_PREFIX ."attachments` WHERE (". implode($oper, $_sql).")";
		$dbCore->query($query);
		while ($dbCore->nextRecord())
		{
			$attachmentidlist[] = $dbCore->Record["attachmentid"];
		}
		
		//print_r($attachmentidlist);
		$_end = fetchmicrotime();
		return $attachmentidlist;
}


if ($eventaction == "purgeattachments")
{
	renderTicketTree();

	    $template->assign("calendar", true);

		$interface->adminHeader($_SWIFT["language"]["tickets"]. " > ".$_SWIFT["language"]["pattach"] , 1);

		$interface->adminNavBar('<a href="index.php?_m=tickets&_a=purgeattachments" title="'.$_SWIFT["language"]["tickets"].'">'.$_SWIFT["language"]["tickets"].'</a> &raquo; <a href="index.php?_m=tickets&_a=purgeattachments" title="'.$_SWIFT["language"]["pattach"].'">'.$_SWIFT["language"]["pattach"], $_SWIFT["language"]["dis_pattch"] , 5);
		
		//echo "test DELETECONFIRM" . $_GET["delaconfirm"];
		if($_GET["delaconfirm"] == "1")
		{
			printInfoBox($_SWIFT["language"]["delattachconfirm"]);
		}

		if ($_POST["step"] == 1)
		{
					$_searchresults = attachentsearch($_POST["searchrules"], $_POST["ruleoptions"]);

					if (empty($_searchresults))
					{
						$infomessage = $_SWIFT["language"]["zeroresults"];
						//exit;
					}
					$infomessage  = sprintf($_SWIFT["language"]["attachresult"], count($_searchresults));

					printInfoBox($infomessage);
					printErrorBox($errormessage);
					
					printMainTableHeader(htmlspecialchars("Attachments Table") , "100%", "0", "0", "float: left; position: relative;");
					$name = "attachlist";

					printFormStart($name, "index.php", "POST", false, "", "");
					
							echo '<tr>'.SWIFT_CRLF;

							echo '<td class="tabletitlerow" align="center" valign="middle" width=20 nowrap><input type="checkbox" name="allselect" class="swiftcheckbox" onClick="javascript:toggleAll(document.'.$name.');"></td>'.SWIFT_CRLF;
							
							echo '<td class="tabletitlerow">Attachment ID</td><td class="tabletitlerow">Ticket ID</td><td class="tabletitlerow">File Size</td><td class="tabletitlerow">File name</td>'.SWIFT_CRLF;
							
							echo '</tr>'.SWIFT_CRLF;

							$dbCore->query("SELECT attachments.*, tickets.ticketmaskid AS ticketmaskid FROM `". TABLE_PREFIX ."attachments` AS attachments LEFT JOIN `". TABLE_PREFIX ."tickets` AS tickets ON (attachments.ticketid = tickets.ticketid) WHERE attachments.attachmentid IN (". buildIN($_searchresults) .");");

							while ($dbCore->nextRecord())
							{
								$id = $dbCore->Record["attachmentid"];
							echo '<tr class="'. getRowBG() .'">' . SWIFT_CRLF;
							
							echo '<td align="center" valign="middle">'. "<input type='checkbox' name='itemid[]' value='$id' class=\"swiftcheckbox\" ><input type='hidden' name='itemhighlight{$id}' value='0'>" .'</td>'.SWIFT_CRLF;
							
							echo "<td>" . $dbCore->Record["attachmentid"] . "</td><td>" . iif($_SWIFT["settings"]["t_eticketid"]=="seq",$dbCore->Record["ticketid"], $dbCore->Record["ticketmaskid"]) . "</td><td>" . formattedSize($dbCore->Record["filesize"])."</td><td>" . 
							$dbCore->Record["filename"]. "</td></tr>";
							}
						printSubmitRow($_SWIFT["language"]["delete"], "5");
						printMainTableFooter();

						addHiddenField("_m", "tickets");
						addHiddenField("_a", "purgeattachments");
						addHiddenField("type", "delete");
						printFormEnd();
			} else {
							
	if ($_POST["type"] == 'delete')
	{
		//------delete attachments physicaly-------
		$_attachlist = $_POST["itemid"];

		$dir = "./files/";
		$_ticketids = array();

		$dbCore->query("SELECT `storefilename`, `ticketid` FROM `". TABLE_PREFIX ."attachments` WHERE `attachmentid` IN (". buildIN($_attachlist) .");");

		while ($dbCore->nextRecord())
		{
			$attach = $dbCore->Record["storefilename"];
			$_ticketids[] = $dbCore->Record["ticketid"];
			//echo "File : ". $attach . "<br />";

			if ($deldir = opendir($dir))
			{
				while (false !== ($file = readdir($deldir)))
				{ 
				if ($file != "." && $file != ".." && $file != "index.html" && $file == $attach) 
				{ 
							//	echo "filename: $file <br /><br />";
					@unlink("./files/".$val); 
					//	echo "File Deleted<br/>";
				}}
		
			closedir($deldir); 
		}
		//delete from database------
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."attachmentchunks` WHERE `attachmentid` IN (". buildIN($_attachlist) .");");

		//echo "chunks deleted<br/>";
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."attachments` WHERE `attachmentid` IN (". buildIN($_attachlist) .");");

		//echo "Attachnets database cleared<br/>";
		//clear tickets data for attachment....

		$_uticketid = array();
		foreach($_ticketids as $key=>$val)
		{

		//echo "TicketID" . $val;

		$count=$dbCore->queryFetch("SELECT COUNT(*) AS count FROM `". TABLE_PREFIX ."attachments` WHERE `ticketid`= '". intval($val) ."';");

		//echo "Count". $count["count"] ."<br/>";
	
		if(empty($count["count"]))
		{
			$_uticketid[] = intval($val);
		}
		}

		$dbCore->shutDownQuery("UPDATE `". TABLE_PREFIX ."tickets` SET `hasattachments` = '0' WHERE `ticketid` IN (". buildIN($_uticketid) .");");

		//header("location: index.php?_m=tickets&_a=purgeattachments&delaresult=1");
		

	}
	printInfoBox($_SWIFT["language"]["delattachconfirm"]);
	}
		?>

		<script type="text/javascript">
			var cruleindex = 1;
			function newSearchAttach()
			{
				var rowElement = document.createElement("div");
				rowElement.id = "rulerow"+cruleindex;
				var rowMod = cruleindex%2;
				rowElement.className = "searchrule"+rowMod;
				var tparent = browserObject("ruleparent");
				if (!tparent)
				{
					return false;
				}

				tparent.appendChild(rowElement);
				updateRuleHTML(cruleindex, "filename");
				cruleindex++;
			}

			function removeRuleRow(ruleindex)
			{
				var tparent = browserObject("ruleparent");
				if (!tparent)
				{
					return false;
				}

				var rowElement = browserObject("rulerow"+ruleindex);
				if (!rowElement)
				{
					return false;
				}

				tparent.removeChild(rowElement);
			}

			function updateRuleHTML(ruleindex, fieldtype)
			{
				var returnResult;

				returnResult = '<table border="0" cellpadding="3" cellspacing="1" width="100%"><tr><td align="left" width="1"><a href="javascript:void(0);" onClick="javascript:removeRuleRow(\''+ruleindex+'\');"><img src="<?=$_SWIFT["themepath"]?>icon_deletesmall.gif" title="<?=$_SWIFT["language"]["deletecriteria"]?>" border="0" /></a></td><td align="left" width="1"><select name="searchrules['+ ruleindex +'][0]" class="swiftselect" onChange="javascript:updateRuleHTML(\''+ ruleindex +'\', this.options[this.selectedIndex].value);">';
				returnResult += '<optgroup label="<?=$_SWIFT["language"]["attach"]?>">';
				returnResult += '<option value="filename"'+selectedStatus(fieldtype, "filename")+'><?=addslashes($_SWIFT["language"]["filename"])?></option>';
				returnResult += '<option value="size"'+selectedStatus(fieldtype, "size")+'><?=addslashes($_SWIFT["language"]["size"])?></option>';
				returnResult += '<option value="ticketid"'+selectedStatus(fieldtype, "ticketid")+'><?=addslashes($_SWIFT["language"]["byticketid"])?></option>';
				returnResult += '<option value="dateline"'+selectedStatus(fieldtype, "dateline")+'><?=addslashes($_SWIFT["language"]["bydate"])?></option>';
				returnResult += '</optgroup>';
				
				returnResult += '</select>';

				returnResult += "</td>";

				if (fieldtype == "filename")
				{
					returnResult += getOperatorHTML(ruleindex, "string")+getQueryHTML(ruleindex, "textentire");
				} else if (fieldtype == "size") {
					returnResult += getOperatorHTML(ruleindex, "int")+getQueryHTML(ruleindex, "textentire");
				} else if (fieldtype == "dateline") {
					returnResult += getOperatorHTML(ruleindex, "cal")+getQueryHTML(ruleindex, "cal");
				} else if (fieldtype == "ticketid")
				{ 
					returnResult += getOperatorHTML(ruleindex, "bool")+getQueryHTML(ruleindex, "textentire");
				}

				var cfield = fieldtype.substring(0,7);
				if (cfield == "cfield_")
				{
					returnResult += getOperatorHTML(ruleindex, "resstring")+getQueryHTML(ruleindex, "text");
				}

				var dRow = browserObject("rulerow"+ruleindex);
				if (!dRow)
				{
					return;
				}

				dRow.innerHTML = returnResult+'</tr></table>';
			}

			function selectedStatus(fieldtype, fieldvalue)
			{
				if (fieldtype == fieldvalue)
				{
					return " selected";
				}
			}

			function getOperatorHTML(ruleindex, optype)
			{
				if (!ruleindex)
				{
					return;
				}

				if (optype == "string")
				{
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_CONTAINS?>" selected><?=$_SWIFT["language"]["opcontains"]?></option><option value="<?=OP_NOTCONTAINS?>"><?=addslashes($_SWIFT["language"]["opnotcontains"])?></option><option value="<?=OP_EQUAL?>"><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"><?=$_SWIFT["language"]["opnotequal"]?></option></select></td>';
				} else if (optype == "int") {
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_GREATER?>"><?=$_SWIFT["language"]["opgreater"]?></option><option value="<?=OP_LESS?>"><?=$_SWIFT["language"]["opless"]?></option><option value="<?=OP_EQUAL?>" selected><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"><?=$_SWIFT["language"]["opnotequal"]?></option></select></td>';
				} else if (optype == "cal") {
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_GREATER?>" selected><?=$_SWIFT["language"]["opgreater"]?></option><option value="<?=OP_LESS?>"><?=$_SWIFT["language"]["opless"]?></option></select></td>';
				}else if (optype == "bool") {
					return '<td align="left" width="1"><select name="searchrules['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_EQUAL?>" selected><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"><?=$_SWIFT["language"]["opnotequal"]?></option></select></td>';
				}
			}

			function getQueryHTML(ruleindex, querytype)
			{
				if (!ruleindex)
				{
					return;
				}

				var returnResult = '<td align="left">';
				
				if (querytype == "textentire") {
					returnResult += '<input type="text" size="20" class="swifttext" name="searchrules['+ ruleindex +'][2]" style="width:50%;" /><span class="smalltext">&nbsp;&nbsp;<?=addslashes($_SWIFT["language"]["squerydesc"])?></span>';
				} else if (querytype == "cal") {
					returnResult += '<input type="text" name="searchrules['+ruleindex+'][2]" id="rulecal'+ ruleindex +'" onclick="return showCalendar(\'rulecal'+ ruleindex +'\', \'<?=iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y")?>\');" size="12" readonly="1" value="" class="swifttext"/>&nbsp;<img src="<?=$_SWIFT["themepath"]?>calendar.gif" onclick="return showCalendar(\'rulecal'+ ruleindex +'\', \'<?=iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y")?>\');" style="cursor: pointer;" align="absmiddle"/>';
				}
				
				return returnResult+'</td>';
			}
		</script>
		<?

		printFormStart();
		printMainTableHeader($_SWIFT["language"]["searchrules"]);

		echo '<tr class="'. getRowBG() .'">
		<td align="left" colspan="2"><span class="smalltext"><div id="ruleparent"></div></span></td></tr>';

		echo '<tr class="'. getRowBG() .'">
		<td align="left" colspan="2"><span class="smalltext"><a href="javascript:newSearchAttach();"><img src="'. $_SWIFT["themepath"] .'icon_add.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["newrule"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label for="ruleall"><input type="radio" name="ruleoptions" value="all" id="ruleall" checked>'. $_SWIFT["language"]["smatchall"] .'</label>&nbsp;<label for="ruleany"><input type="radio" name="ruleoptions" value="any" id="ruleany">'. $_SWIFT["language"]["smatchany"] .'</label></span></td></tr>';

		printSubmitRow($_SWIFT["language"]["search"]);

		printMainTableFooter();

		addHiddenField("_m", "tickets");
		addHiddenField("_a", "purgeattachments");
		addHiddenField("step", "1");
		printFormEnd();
		?>
		<script type="text/javascript">
			newSearchAttach();
		</script>
		<?  }
		
	$interface->adminFooter();
}

?>